// Generator 配合 Promise 的异步方案

export default () => {
  function ajax(url) {
    return new Promise(function (resolver, reject) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "json";
      xhr.onload = function () {
        if (this.status === 200) {
          resolver(this.response);
        } else {
          reject(new Error(this.statusText))
        }
      };

      xhr.send();
    })
  }

  function* main() {
    const users = yield ajax("/api/users.json");
    console.log(users);

    const requests = yield ajax("/api/posts.json");
    console.log(requests);
  }

  const g = main();

  const result = g.next(); // 获取到一个promise对象

  // console.log(result);
  result.value.then((res) => {
    // console.log(res);
    const req = g.next(res)
    req.value.then(res1 => {
      g.next(res1)
    })

  })
}